<template>
  <div class="file-preview-panel">
    <div class="preview-header">
      <div class="header-info">
        <el-icon><Document /></el-icon>
        <span class="file-name">{{ fileName }}</span>
        <el-tag size="small" type="info">{{ fileExtension || 'unknown' }}</el-tag>
      </div>
      
      <div class="header-actions">
        <el-button-group size="small">
          <el-tooltip content="复制内容">
            <el-button :icon="CopyDocument" @click="copyContent" text />
          </el-tooltip>
          <el-tooltip content="下载文件">
            <el-button :icon="Download" @click="downloadFile" text />
          </el-tooltip>
          <el-tooltip content="全屏预览">
            <el-button :icon="FullScreen" @click="toggleFullscreen" text />
          </el-tooltip>
        </el-button-group>
      </div>
    </div>

    <div class="preview-content">
      <el-scrollbar height="100%">
        <!-- Text/Code Preview -->
        <div v-if="isTextFile" class="text-preview">
          <div class="preview-toolbar">
            <div class="toolbar-left">
              <el-text size="small" type="info">
                {{ contentStats.lines }} 行, {{ contentStats.characters }} 字符
              </el-text>
            </div>
            <div class="toolbar-right">
              <el-switch
                v-model="showLineNumbers"
                size="small"
                active-text="行号"
                inactive-text=""
              />
              <el-switch
                v-model="wordWrap"
                size="small"
                active-text="换行"
                inactive-text=""
              />
            </div>
          </div>
          
          <div class="code-container">
            <pre 
              :class="[
                'code-content',
                { 'with-line-numbers': showLineNumbers, 'word-wrap': wordWrap }
              ]"
            ><code 
              v-if="highlightedContent" 
              v-html="highlightedContent"
            ></code><code v-else>{{ content }}</code></pre>
          </div>
        </div>

        <!-- Image Preview -->
        <div v-else-if="isImageFile" class="image-preview">
          <div class="image-container">
            <el-image
              :src="imageDataUrl"
              :alt="fileName"
              fit="contain"
              :preview-src-list="[imageDataUrl]"
              :initial-index="0"
              preview-teleported
            />
          </div>
          <div class="image-info">
            <el-text size="small" type="info">
              点击图片可放大查看
            </el-text>
          </div>
        </div>

        <!-- Binary File Preview -->
        <div v-else-if="isBinaryFile" class="binary-preview">
          <div class="binary-info">
            <el-icon size="48"><Document /></el-icon>
            <h4>二进制文件</h4>
            <p>无法预览此类型的文件内容</p>
            <el-button type="primary" @click="downloadFile">
              下载文件
            </el-button>
          </div>
          
          <div class="hex-preview" v-if="showHexPreview">
            <h5>十六进制预览 (前 {{ hexPreviewSize }} 字节)</h5>
            <div class="hex-content">
              <pre>{{ hexContent }}</pre>
            </div>
          </div>
        </div>

        <!-- Large File Warning -->
        <div v-else-if="isLargeFile" class="large-file-warning">
          <el-alert
            title="文件过大"
            :description="`文件大小为 ${formatFileSize(content.length)}，为了性能考虑，建议下载后查看`"
            type="warning"
            :closable="false"
          />
          <div class="large-file-actions">
            <el-button type="primary" @click="downloadFile">
              下载文件
            </el-button>
            <el-button @click="forcePreview">
              强制预览
            </el-button>
          </div>
        </div>

        <!-- Empty File -->
        <div v-else-if="content.length === 0" class="empty-file">
          <el-empty description="文件为空" />
        </div>

        <!-- Error State -->
        <div v-else class="preview-error">
          <el-alert
            title="预览失败"
            description="无法预览此文件，请尝试下载查看"
            type="error"
            :closable="false"
          />
        </div>
      </el-scrollbar>
    </div>
  </div>
</template>

<script setup lang="ts">
import { computed, ref, onMounted } from 'vue'
import { 
  Document, 
  CopyDocument, 
  Download, 
  FullScreen 
} from '@element-plus/icons-vue'
import { ElMessage } from 'element-plus'

interface Props {
  content: string
  filePath: string
  versionId: string | null
}

const props = defineProps<Props>()

// Local state
const showLineNumbers = ref(true)
const wordWrap = ref(false)
const showHexPreview = ref(false)
const hexPreviewSize = ref(256)
const highlightedContent = ref<string | null>(null)
const imageDataUrl = ref<string | null>(null)

// Computed properties
const fileName = computed(() => {
  const parts = props.filePath.split('/')
  return parts[parts.length - 1]
})

const fileExtension = computed(() => {
  const name = fileName.value
  const lastDot = name.lastIndexOf('.')
  return lastDot > 0 ? name.substring(lastDot + 1).toLowerCase() : null
})

const isTextFile = computed(() => {
  if (!fileExtension.value) return true
  
  const textExtensions = new Set([
    'txt', 'md', 'json', 'xml', 'html', 'css', 'js', 'ts', 'vue', 'jsx', 'tsx',
    'py', 'java', 'c', 'cpp', 'cs', 'php', 'rb', 'go', 'rs', 'sh', 'bat',
    'yml', 'yaml', 'toml', 'ini', 'cfg', 'conf', 'log', 'sql', 'csv'
  ])
  
  return textExtensions.has(fileExtension.value)
})

const isImageFile = computed(() => {
  if (!fileExtension.value) return false
  
  const imageExtensions = new Set(['png', 'jpg', 'jpeg', 'gif', 'svg', 'bmp', 'webp'])
  return imageExtensions.has(fileExtension.value)
})

const isBinaryFile = computed(() => {
  return !isTextFile.value && !isImageFile.value
})

const isLargeFile = computed(() => {
  return props.content.length > 1024 * 1024 // 1MB
})

const contentStats = computed(() => {
  const lines = props.content.split('\n').length
  const characters = props.content.length
  const words = props.content.split(/\s+/).filter(word => word.length > 0).length
  
  return { lines, characters, words }
})

const hexContent = computed(() => {
  if (!isBinaryFile.value) return ''
  
  const bytes = new TextEncoder().encode(props.content.substring(0, hexPreviewSize.value))
  let hex = ''
  
  for (let i = 0; i < bytes.length; i += 16) {
    // Address
    const address = i.toString(16).padStart(8, '0').toUpperCase()
    hex += `${address}  `
    
    // Hex bytes
    const hexBytes = []
    const asciiBytes = []
    
    for (let j = 0; j < 16; j++) {
      if (i + j < bytes.length) {
        const byte = bytes[i + j]
        hexBytes.push(byte.toString(16).padStart(2, '0').toUpperCase())
        asciiBytes.push(byte >= 32 && byte <= 126 ? String.fromCharCode(byte) : '.')
      } else {
        hexBytes.push('  ')
        asciiBytes.push(' ')
      }
    }
    
    hex += hexBytes.slice(0, 8).join(' ') + '  '
    hex += hexBytes.slice(8).join(' ') + '  '
    hex += '|' + asciiBytes.join('') + '|\n'
  }
  
  return hex
})

// Methods
async function copyContent() {
  try {
    await navigator.clipboard.writeText(props.content)
    ElMessage.success('内容已复制到剪贴板')
  } catch (err) {
    ElMessage.error('复制失败')
  }
}

function downloadFile() {
  const blob = new Blob([props.content], { type: 'text/plain' })
  const url = URL.createObjectURL(blob)
  const a = document.createElement('a')
  a.href = url
  a.download = fileName.value
  document.body.appendChild(a)
  a.click()
  document.body.removeChild(a)
  URL.revokeObjectURL(url)
  
  ElMessage.success('文件下载已开始')
}

function toggleFullscreen() {
  // TODO: Implement fullscreen preview
  ElMessage.info('全屏功能开发中')
}

function forcePreview() {
  // Force preview large file
  ElMessage.warning('强制预览大文件可能会影响性能')
}

function formatFileSize(size: number): string {
  const units = ['B', 'KB', 'MB', 'GB']
  let unitIndex = 0
  let fileSize = size
  
  while (fileSize >= 1024 && unitIndex < units.length - 1) {
    fileSize /= 1024
    unitIndex++
  }
  
  return `${fileSize.toFixed(unitIndex === 0 ? 0 : 1)} ${units[unitIndex]}`
}

async function highlightCode() {
  // Simple syntax highlighting for common file types
  if (!isTextFile.value || !fileExtension.value) return
  
  try {
    // Simplified syntax highlighting without complex regex
    // In a real implementation, you would use a library like Prism.js or highlight.js
    highlightedContent.value = props.content
  } catch (err) {
    console.warn('Syntax highlighting failed:', err)
  }
}

function loadImagePreview() {
  if (!isImageFile.value) return
  
  try {
    // For base64 encoded images or data URLs
    if (props.content.startsWith('data:')) {
      imageDataUrl.value = props.content
    } else {
      // Convert binary content to data URL
      const blob = new Blob([props.content])
      imageDataUrl.value = URL.createObjectURL(blob)
    }
  } catch (err) {
    console.warn('Failed to load image preview:', err)
  }
}

// Lifecycle
onMounted(() => {
  if (isTextFile.value) {
    highlightCode()
  } else if (isImageFile.value) {
    loadImagePreview()
  }
})
</script>

<style scoped>
.file-preview-panel {
  height: 100%;
  display: flex;
  flex-direction: column;
}

.preview-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 12px 16px;
  border-bottom: 1px solid var(--el-border-color);
  background-color: var(--el-bg-color-page);
}

.header-info {
  display: flex;
  align-items: center;
  gap: 8px;
}

.file-name {
  font-weight: 500;
  color: var(--el-text-color-primary);
}

.preview-content {
  flex: 1;
  height: calc(100% - 49px);
}

.text-preview {
  height: 100%;
  display: flex;
  flex-direction: column;
}

.preview-toolbar {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 8px 16px;
  border-bottom: 1px solid var(--el-border-color-lighter);
  background-color: var(--el-bg-color-page);
}

.toolbar-right {
  display: flex;
  align-items: center;
  gap: 12px;
}

.code-container {
  flex: 1;
  overflow: auto;
}

.code-content {
  margin: 0;
  padding: 16px;
  font-family: 'Courier New', 'Monaco', 'Menlo', monospace;
  font-size: 13px;
  line-height: 1.5;
  background-color: var(--el-bg-color);
  color: var(--el-text-color-primary);
  white-space: pre;
  overflow-x: auto;
}

.code-content.word-wrap {
  white-space: pre-wrap;
  word-break: break-all;
}

.code-content.with-line-numbers {
  counter-reset: line-number;
}

.code-content.with-line-numbers::before {
  content: counter(line-number);
  counter-increment: line-number;
  position: absolute;
  left: 0;
  width: 40px;
  text-align: right;
  color: var(--el-text-color-placeholder);
  border-right: 1px solid var(--el-border-color-lighter);
  padding-right: 8px;
  margin-right: 12px;
}

.image-preview {
  padding: 16px;
  text-align: center;
}

.image-container {
  margin-bottom: 12px;
}

.binary-preview {
  padding: 16px;
  text-align: center;
}

.binary-info {
  margin-bottom: 24px;
}

.binary-info h4 {
  margin: 12px 0 8px 0;
  color: var(--el-text-color-primary);
}

.binary-info p {
  margin: 0 0 16px 0;
  color: var(--el-text-color-regular);
}

.hex-preview {
  text-align: left;
  margin-top: 24px;
  padding-top: 16px;
  border-top: 1px solid var(--el-border-color);
}

.hex-preview h5 {
  margin: 0 0 12px 0;
  color: var(--el-text-color-primary);
}

.hex-content {
  background-color: var(--el-bg-color-page);
  border: 1px solid var(--el-border-color);
  border-radius: 4px;
  padding: 12px;
  overflow-x: auto;
}

.hex-content pre {
  margin: 0;
  font-family: 'Courier New', monospace;
  font-size: 12px;
  line-height: 1.4;
  color: var(--el-text-color-primary);
}

.large-file-warning {
  padding: 16px;
  text-align: center;
}

.large-file-actions {
  margin-top: 16px;
  display: flex;
  justify-content: center;
  gap: 12px;
}

.empty-file,
.preview-error {
  padding: 16px;
  text-align: center;
}

/* Syntax highlighting styles */
:deep(.keyword) {
  color: var(--el-color-primary);
  font-weight: 600;
}

:deep(.comment) {
  color: var(--el-text-color-placeholder);
  font-style: italic;
}

:deep(.string) {
  color: var(--el-color-success);
}

:deep(.property) {
  color: var(--el-color-warning);
}

:deep(.boolean) {
  color: var(--el-color-danger);
}

:deep(.number) {
  color: var(--el-color-info);
}

/* Responsive adjustments */
@media (max-width: 768px) {
  .preview-header {
    flex-direction: column;
    align-items: stretch;
    gap: 8px;
  }
  
  .preview-toolbar {
    flex-direction: column;
    align-items: stretch;
    gap: 8px;
  }
  
  .toolbar-right {
    justify-content: center;
  }
  
  .code-content {
    font-size: 12px;
    padding: 12px;
  }
}
</style>